package com.zjt.smart.util;

import java.lang.reflect.Array;

/**
 * @author zhengjianting
 * @time 2017/11/2 0002 下午 7:15
 */

public class StringUtils {

    /*
     * 功能：获取arr1中下标从startIndexInclusive到endIndexExclusive的子数组，不包括endIndexExclusive
     */

    public static byte[] subarray(byte[] array, int startIndexInclusive,
                                  int endIndexExclusive) {
        if (array == null) {
            return null;
        }
        if (startIndexInclusive < 0) {
            startIndexInclusive = 0;
        }
        if (endIndexExclusive > array.length) {
            endIndexExclusive = array.length;
        }
        int newSize = endIndexExclusive - startIndexInclusive;
        Class type = array.getClass().getComponentType();
        if (newSize <= 0) {
            return (byte[]) Array.newInstance(type, 0);
        }
        byte[] subarray = (byte[]) Array.newInstance(type, newSize);
        System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
        return subarray;
    }

    /*
     *
     * 功能：将arr2追加到arr1尾部：
     */
    public static byte[] addAll(byte[] array1, byte[] array2) {
        if (array1 == null) {
            return array2;
        } else if (array2 == null) {
            return array1;
        }
        byte[] joinedArray = (byte[]) Array.newInstance(array1.getClass()
                .getComponentType(), array1.length + array2.length);
        System.arraycopy(array1, 0, joinedArray, 0, array1.length);
        System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
        return joinedArray;
    }
}
